package com.example.zhish.newsasync_demo001;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.LruCache;
import android.widget.ImageView;
import android.widget.ListView;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashSet;
import java.util.List;
import java.util.Set;


/**
 * Created by zhish on 2016/4/12.
 */
public class ImageLoader {

    private ImageView imageView;
    private String url;

    private ListView mListView;
    private Set<MyAsyncTask> mTask;

    //创建cache
    private LruCache<String, Bitmap> lruCache;

    public ImageLoader(ListView listView) {

        mListView = listView;
        mTask = new HashSet<>();
        int maxMemory = (int) Runtime.getRuntime().maxMemory();
        int cacheSize = maxMemory / 4;
        lruCache = new LruCache<String, Bitmap>(cacheSize) {
            @Override
            protected int sizeOf(String key, Bitmap value) {
                //在每次存入缓存的时候调用
                return value.getByteCount();
            }
        };
    }

    //加入到缓存
    public void addBitmapCache(String url, Bitmap bitmap) {
        if (getBitmapFromCache(url) == null) {
            lruCache.put(url, bitmap);
        }
    }

    //从缓存中获取出来
    public Bitmap getBitmapFromCache(String url) {
        return lruCache.get(url);
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (imageView.getTag().equals(url)) {
                imageView.setImageBitmap((Bitmap) msg.obj);
            }

        }
    };

    /**
     * 使用线程池的方式加载图片
     *
     * @param imageView
     * @param url
     */
    public void showImageByThread(ImageView imageView, final String url) {
        this.imageView = imageView;
        this.url = url;
        new Thread() {
            @Override
            public void run() {
                super.run();
                Bitmap bitmap = getBitmap(url);
                Message message = new Message();
                message.obj = bitmap;
                handler.sendMessage(message);

            }
        }.start();
    }

    public Bitmap getBitmap(String urlString) {
        Bitmap bitmap;
        InputStream is = null;
        try {
            URL url = new URL(urlString);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            is = new BufferedInputStream(connection.getInputStream());
            bitmap = BitmapFactory.decodeStream(is);
            connection.disconnect();
            return bitmap;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    //加载指定的url对应的图片
    public void loadImages(int start, int end) {
        for (int i = start; i < end; i++) {
            String url = NewsAdapter.URLS[i];

            //从缓存中取出图片
            Bitmap bitmap = getBitmapFromCache(url);
            //如果缓存中没有，就要从网上下载
            if (bitmap == null) {
                MyAsyncTask task = new MyAsyncTask(url);
                task.execute(url);


            } else {
                ImageView imageView = (ImageView) mListView.findViewWithTag(url);
                imageView.setImageBitmap(bitmap);
            }
        }
    }

    public void showImagebyAsyncTask(ImageView imageView, final String url) {
        //从缓存中取出图片
        Bitmap bitmap = getBitmapFromCache(url);
        //如果缓存中没有，就要从网上下载
        if (bitmap == null) {
            imageView.setImageResource(R.mipmap.ic_launcher);
            //new MyAsyncTask(imageView, url).execute(url);
        } else {
            imageView.setImageBitmap(bitmap);
        }

    }

    public void cancelAllTask() {
        if(mTask != null){
            for (MyAsyncTask task : mTask) {
                task.cancel(false);
            }
        }

    }

    class MyAsyncTask extends AsyncTask<String, Void, Bitmap> {

        private ImageView imageView;
        private String url;

        public MyAsyncTask(ImageView imageView, String url) {
            this.imageView = imageView;
            this.url = url;
            mTask.add(this);
        }

        public MyAsyncTask(String url) {
            this.url = url;
            mTask.add(this);
        }

        @Override
        protected Bitmap doInBackground(String... params) {

            //从网络获取图片
            Bitmap bitmap = getBitmap(params[0]);
            if (bitmap != null) {
                //将不再缓存中的bitmap加入缓存中
                addBitmapCache(url, bitmap);
            }

            return bitmap;
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);
//            if (imageView.getTag().equals(url)) {
//                imageView.setImageBitmap(bitmap);
//            }
            ImageView imageView = (ImageView) mListView.findViewWithTag(url);
            if (imageView != null && bitmap != null) {
                imageView.setImageBitmap(bitmap);
            }
            mTask.remove(this);
        }
    }
}
